<template>
  <div class="mbti-test" v-if="isLoggedIn">
    <h2 class="title">MBTI 测试</h2>
    <div class="question-count">
      第 {{ currentIndex + 1 }} 题 / 共 {{ questions.length }} 题
    </div>

    <div class="question-text">{{ currentQuestion.text }}</div>

    <el-radio-group v-model="answers[currentIndex]" style="margin: 20px 0;">
      <el-radio :label="'A'">{{ currentQuestion.A }}</el-radio>
      <el-radio :label="'B'">{{ currentQuestion.B }}</el-radio>
    </el-radio-group>

    <div class="buttons">
      <el-button :disabled="currentIndex === 0" @click="prevQuestion" style="margin-right: 10px;">
        上一题
      </el-button>

      <el-button
          v-if="currentIndex < questions.length - 1"
          type="primary"
          :disabled="!answers[currentIndex]"
          @click="nextQuestion"
      >
        下一题
      </el-button>

      <el-button
          v-else
          type="success"
          :disabled="!answers[currentIndex]"
          @click="submitAnswers"
      >
        提交并查看结果
      </el-button>
    </div>
  </div>

  <div v-else class="not-logged-in">
    <p>请先登录后再进行 MBTI 测试。</p>
    <el-button type="primary" @click="goLogin">前往登录</el-button>
  </div>
</template>

<script>
import { ref, computed, onMounted } from "vue";
import { questions } from "@/data/questions";
import { ElMessage } from "element-plus";
import axios from "axios";

export default {
  setup() {
    const currentIndex = ref(0);
    const answers = ref(Array(questions.length).fill(null));
    const currentQuestion = computed(() => questions[currentIndex.value]);
    const isLoggedIn = ref(false);

    onMounted(() => {
      isLoggedIn.value = !!localStorage.getItem("loggedIn");
    });

    const nextQuestion = () => {
      if (currentIndex.value < questions.length - 1) {
        currentIndex.value++;
      }
    };

    const prevQuestion = () => {
      if (currentIndex.value > 0) {
        currentIndex.value--;
      }
    };

    const submitAnswers = async () => {
      // 计算MBTI类型
      const score = { EI: 0, SN: 0, TF: 0, JP: 0 };
      questions.forEach((q, i) => {
        if (answers.value[i] === q.direction) {
          score[q.dimension]++;
        }
      });

      const type =
          (score.EI >= 5 ? "E" : "I") +
          (score.SN >= 5 ? "S" : "N") +
          (score.TF >= 5 ? "T" : "F") +
          (score.JP >= 5 ? "J" : "P");

      // 从localStorage取学生ID
      const studentIdStr = localStorage.getItem("studentId");
      if (!studentIdStr) {
        ElMessage.error("未检测到学生ID，请重新登录");
        return;
      }
      const studentId = Number(studentIdStr);
      if (!studentId) {
        ElMessage.error("学生ID无效，请重新登录");
        return;
      }

      // 准备提交数据，和后端SubmitAnswerDTO对应
      const payload = {
        studentId,
        mbtiType: type,
        answers: answers.value.map((ans, idx) => ({
          questionId: questions[idx].id,
          answer: ans,
        })),
      };

      try {
        await axios.post("http://localhost:8081/api/mbti/submit", payload);

        localStorage.setItem("mbtiResult", JSON.stringify({ type, answers: answers.value }));
        ElMessage.success("测试完成，结果已提交并保存，请点击“我的结果”查看");
      } catch (error) {
        console.error("提交失败:", error);
        ElMessage.error("提交失败，请稍后重试");
      }
    };

    const goLogin = () => {
      window.location.href = "/login";
    };

    return {
      currentIndex,
      questions,
      answers,
      currentQuestion,
      nextQuestion,
      prevQuestion,
      submitAnswers,
      isLoggedIn,
      goLogin,
    };
  },
};
</script>

<style scoped>
.mbti-test {
  max-width: 500px;
  margin: 40px auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.title {
  text-align: center;
  margin-bottom: 20px;
  font-weight: 600;
  font-size: 24px;
}

.question-count {
  font-weight: 600;
  margin-bottom: 10px;
  text-align: center;
}

.question-text {
  font-size: 18px;
  font-weight: 500;
}

.buttons {
  text-align: center;
}

.not-logged-in {
  text-align: center;
  padding: 100px;
  font-size: 18px;
  color: #666;
}
</style>
